package net.mikoo.seals.api.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.api.model.ResultType;
import net.mikoo.seals.api.model.workflow.GetPartyListRequest;
import net.mikoo.seals.api.model.workflow.GetPartyListResponse;
import net.mikoo.seals.biz.service.SealServices;
import net.mikoo.seals.biz.service.WorkflowService;
import net.mikoo.seals.model.Seal;
import net.mikoo.seals.model.Workflow;

@Controller
public class WorkflowController {

	private static Logger logger = LoggerFactory.getLogger(WorkflowController.class);
	
	@Autowired
	private WorkflowService workflowService;
	
	@Autowired
	private SealServices sealServices;
	
	@RequestMapping("/workflow/getPartyList")
	@ResponseBody
	public GetPartyListResponse getPartyList(GetPartyListRequest request, HttpServletRequest httpRequest) {
		GetPartyListResponse result = new GetPartyListResponse();
		try {
			
			if(request == null) {
				throw new IllegalArgumentException("request");
			}
			
			if(request.getSealId() == null) {
				throw new IllegalArgumentException("request.sealId");
			}
			
			Seal seal = sealServices.getInfoById(request.getSealId());
			if(seal == null) {
				throw new IllegalStateException("印章不存在");
			}
			Workflow workflow = null;
			Workflow specialWorkflow = null;
			if(seal.getWorkflowId() != null) {
				workflow = workflowService.getInfoById(seal.getWorkflowId());
			}
			if(seal.getSpecialWorkflowId() != null && "Y".equals(seal.getUseSpecial())) {
				specialWorkflow = workflowService.getInfoById(seal.getSpecialWorkflowId());
			}
			
			result = GetPartyListResponse.valueOf(specialWorkflow, workflow);
			result.setResult(ResultType.SUCCESS.getValue());
		}catch(Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		
		return result;
	}
	
}
